package fgoScript.entity;

import aoshiScript.entity.IWuNa;
import chrome.entity.ChromeService;
import commons.entity.Constant;
import commons.entity.CpMissonResults;
import commons.entity.NativeCp;
import commons.util.*;
import destinychild.DaillyMission;
import fgoScript.constant.GameConstant;
import fgoScript.constant.PointInfo;
import fgoScript.entity.guda.AbstractApGudazi;
import fgoScript.entity.guda.AllGudazi;
import fgoScript.entity.guda.ApGudaziFactory;
import fgoScript.entity.guda.EventGudazi;
import fgoScript.entity.panel.FgoFrame;
import fgoScript.exception.AppNeedNextException;
import fgoScript.exception.AppNeedRestartException;
import fgoScript.exception.AppNeedStopException;
import fgoScript.exception.AppNeedUpdateException;
import fgoScript.service.AutoAct;
import fgoScript.service.CommonMethods;
import gudaziEx.entity.RunningChain;
import gudaziEx.service.ClickManage;
import gudaziEx.util.ChainUtil;
import jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.*;
import java.util.concurrent.Future;

/**
 * 咕哒子类
 *
 * @author zmczm
 */
public class Gudazi extends TimerTask {
    private static final Logger LOGGER = LogManager.getLogger(Gudazi.class);
    private static final Logger LOGGER3 = LogManager.getLogger(Gudazi.class);
    private final int DELAY = GameConstant.DELAY;
    private ThreadPoolTaskExecutor circleTPExcutor;
    private ThreadPoolTaskExecutor timerTaskExcutor;
    /**
     * 前台线程
     **/
    private ThreadPoolTaskExecutor frontExcutor;

    public void setFrontExcutor(ThreadPoolTaskExecutor frontExcutor) {
        this.frontExcutor = frontExcutor;
    }

    public void setCircleTPExcutor(ThreadPoolTaskExecutor circleTPExcutor) {
        this.circleTPExcutor = circleTPExcutor;
    }

    public void setTimerTaskExcutor(ThreadPoolTaskExecutor timerTaskExcutor) {
        this.timerTaskExcutor = timerTaskExcutor;
    }

    private IWuNa wuna;
    private ClickManage clickManage;

    public void setClickManage(ClickManage clickManage) {
        this.clickManage = clickManage;
    }

    public void setWuna(IWuNa wuna) {
        this.wuna = wuna;
    }

    private static boolean ifRestart;

    public static boolean isIfRestart() {
        return ifRestart;
    }

    private static void setIfRestart(boolean ifRestart) {
        Gudazi.ifRestart = ifRestart;
    }

    private final boolean IF_ShutDown_BeforeRunable = Boolean.parseBoolean(GameUtil.getValueFromConfig("IF_ShutDown_BeforeRunable"));
    private final boolean IF_LO = Boolean.parseBoolean(GameUtil.getValueFromConfig("IF_LO"));
    private final boolean IF_DC = Boolean.parseBoolean(GameUtil.getValueFromConfig("IF_DC"));
    private final boolean IF_RUNABLE = Boolean.parseBoolean(GameUtil.getValueFromConfig("IF_RUNABLE"));
    private final String IMG_EXTEND = GameConstant.IMG_EXTEND;
    private final String PREFIX = GameUtil.getPreFix();
    private Robot r;
    private int countNum;

    private int[] getFgoRewardArray() {
        return GameUtil.strToIntArray(GameUtil.getValueFromConfig("FgoRewardArray"), false);
    }

    private int[] getFgoSignArray() {
        return GameUtil.strToIntArray(GameUtil.getValueFromConfig("FgoSignArray"), false);
    }

    public Robot getR() {
        return r;
    }

    public void setR(Robot r) {
        this.r = r;
    }

    public void onlyFight() throws Exception {
        GameUtil.colorMonitorList = null;
        String flag = PropertiesUtil.getValueFromSkillsFile("ifRestart");
        boolean stopFlag = false;
        GameUtil.setSTOP_SCRIPT(false);
        for (int i = 0; i < GameConstant.getBattleCount(); i++) {
            timerTaskExcutor.execute(() -> {
                wuna.alwaysClick();
            });
            Color tempColor;
            do {
                tempColor = GameUtil.getScreenPixel(PointInfo.getInstance().getpBlueAttack());
                if (GameUtil.isSTOP_SCRIPT()) {
                    stopFlag = true;
                    break;
                }
                GameUtil.delay(2000);
            } while (!GameUtil.likeEqualColor(PointInfo.getInstance().getcBlueAttack(), tempColor));
            if (stopFlag) {
                wuna.setGO(false);
                break;
            }
            wuna.setGO(false);
            int n = 0;
            while ((n = circleTPExcutor.getActiveCount()) != 0) {
                LOGGER.info("线程个数" + circleTPExcutor.getActiveCount());
                GameUtil.delay(1500);
            }
            try {
                String ifRestart = PropertiesUtil.getValueFromSkillsFile("ifRestart");
                new EventGudazi().fightAndStop(i == 0 && ifRestart.equals("false") ? false : true, 0,0);
            } catch (AppNeedNextException | AppNeedRestartException e) {
                LOGGER.info("无所谓！接着走~");
            }
            LOGGER.info("进入下一个循环！");
        }
    }
    private int getBattleCount(){

            String multiFactor = PropertiesUtil.getValueFromFileNameAndKey("battleCount" , "st_" + NativeCp.getUserName(),Constant.FGO);
            int battleCount = Integer.parseInt(multiFactor.trim());
            return battleCount;
    }
    public void onlyFightForAll() throws Exception {
        GameUtil.colorMonitorList = null;
        String flag = PropertiesUtil.getValueFromSkillsFile("ifRestart");
        boolean stopFlag = false;
        GameUtil.setSTOP_SCRIPT(false);

        for (int i = 0; i < getBattleCount(); i++) {

            timerTaskExcutor.execute(() -> {
                try {
                    wuna.alwaysClickForStrategy("clicks_FGO", null, false, false, false, false, 0, "FGO/", null);
                } catch (AppNeedRestartException e) {
                    LOGGER.error(e.getMessage());
                } catch (AppNeedStopException e) {
                    e.printStackTrace();
                }
            });
            Color tempColor;
            GameUtil.delay(200);
            do {
                if(timerTaskExcutor.getActiveCount()==0){
                    LOGGER.info("点击线程自然结束了，细化战斗结束！");
                    return;
                }
                System.out.println("b点击线程池个数："+timerTaskExcutor.getActiveCount());
                tempColor = GameUtil.getScreenPixel(PointInfo.getInstance().getpBlueAttack());
                if (GameUtil.isSTOP_SCRIPT()) {
                    stopFlag = true;
                    break;
                }
                GameUtil.delay(2000);
            } while ("false".equals(PropertiesUtil.getValueFromSkillsFile("ifBattle")) ||
                    !GameUtil.likeEqualColor(PointInfo.getInstance().getcBlueAttack(), tempColor));

            if (stopFlag) {
                wuna.setGO(false);
                break;
            }
            wuna.setGO(false);
            int n = 0;
            while ((n = circleTPExcutor.getActiveCount()) != 0) {
                LOGGER.info("线程个数" + circleTPExcutor.getActiveCount());
                GameUtil.delay(1500);
            }

            try {
                String ifRestart = PropertiesUtil.getValueFromSkillsFile("ifRestart");
                new AllGudazi().fightAndStop(i == 0 && ifRestart.equals("false") ? false : true, 0,0);
            } catch (AppNeedNextException | AppNeedRestartException e) {
                LOGGER.info("无所谓！接着走~");
            }


            LOGGER.info("进入下一个循环！");
        }
    }

    private void autoClose() {
        circleTPExcutor.execute(() -> {
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                LOGGER.info(GameUtil.getStackMsg(e));
            }
            GameUtil.setGO_FLAG(false);
            LOGGER.error("脚本自然死亡~");
        });
        circleTPExcutor.shutdown();
    }

    public void trainSamllFgo() throws Exception {
        ApGudaziFactory.getInstance("train", "small", null).startAllFgo();
    }

    public static boolean ifGoTrain() {
        boolean ifGo = false;
        int weekDay = ServantSelect.getDayOfWeek();
        Calendar cd = Calendar.getInstance();
        int h = cd.get(Calendar.HOUR_OF_DAY);
        LOGGER.info("WeekDay: " + weekDay);
        ifGo = (weekDay == 3 || weekDay == 6 || weekDay == 7) && (h < 5 || h > 21);
        return ifGo;
    }

    public static void doLoTrain(RunningChain rc, ThreadPoolTaskExecutor timerTaskExcutor, ClickManage clickManage, boolean IF_LO) {
        // 先执行一次训练本
        if (ifGoTrain() && IF_LO) {
            ProcessDealUtil.killAllDnPlayer();
            LOGGER.info("符合条件，开始执行LO_TRAIN!");
            String tempName = rc.getAutoChainName();
            rc.setAutoChainName("LO_TRAIN");
            ChainUtil.saveRunningChain(rc);

            Future ft;
            ft = timerTaskExcutor.submit(new Runnable() {
                @Override
                public void run() {
                    LOGGER.info("执行LO_TRAIN");
                    clickManage.Toggle("LO_TRAIN", true);
                }
            });
            ThreadUtil.waitUntilFutureFinished(ft);

            rc.setAutoChainName(tempName);
            ChainUtil.saveRunningChain(rc);
        }
    }

    private void doLoDecompose(RunningChain rc) {
        // 先执行一次登录分解
        if (IF_LO) {
            LOGGER.info("执行LO_DECOMPOSE");
            String tempName = rc.getAutoChainName();
            rc.setAutoChainName("LO_DECOMPOSE");
            ChainUtil.saveRunningChain(rc);

            Future ft;
            ft = timerTaskExcutor.submit(new Runnable() {
                @Override
                public void run() {
                    clickManage.Toggle("LO_DECOMPOSE", false);
                }
            });
            ThreadUtil.waitUntilFutureFinished(ft);

            rc.setAutoChainName(tempName);
            ChainUtil.saveRunningChain(rc);
        }
    }

    private void doLoDaily(RunningChain rc) {
        // dailyChain 执行挂机 登录 切出
        if (IF_LO) {
            LOGGER.info("执行DailyChain");
            timerTaskExcutor.execute(new Runnable() {
                @Override
                public void run() {
                    clickManage.Toggle(rc.getDailyChainName(), false);
                }
            });
            clickManage.waitUntilShiftOut();
            // 防止卡顿
            clickManage.waitUntilShiftIn();
            clickManage.runMain(rc.getDailyChainName(), false);
            clickManage.waitUntilShiftOut();
        }
    }

    public void goAll() throws Exception {

        // 初始化运行状态文件
        CpMissonResults.initCpStateFile();

        GameUtil.setSTOP_SCRIPT(false);
        ProcessDealUtil.ReconectNet("rzhmy");
        String[] qts = GameUtil.getValueFromConfig("QP_TRAIN_SELECTS").split("_");
        Calendar cd = Calendar.getInstance();
        int h = cd.get(Calendar.HOUR_OF_DAY);
        //执行toptoon签到任务
        if(false){
            ChromeService.GoSignTopToon();
            ProcessDealUtil.closeChrome();
            ChromeService.GoSignTopToon();
            ProcessDealUtil.closeChrome();
            ChromeService.GoCheckTopToon();
            ProcessDealUtil.closeChrome();
        }
        if (h > 24) {
            LOGGER.info("白天不执行登录检测，直接跳过");
        } else {
            if (Boolean.parseBoolean(GameUtil.getValueFromConfig("IF_SIGN"))) {
                signAllFGO();
                ProcessDealUtil.killAllDnPlayer();
            }
        }
        // 执行lo挂机后台任务
        RunningChain rc = ChainUtil.getRunningChain();
        String cornString = rc.getCornString();
        String autoChainName = rc.getAutoChainName();
        String runableModuleName = rc.getRunableModuleName();
        String dailyChainName = rc.getDailyChainName();
        rc.setLogin(true);
        // dailyChainName start
        rc.setAutoChainName(dailyChainName);
        ChainUtil.saveRunningChain(rc);
        // 执行lo一次循环
        doLoDecompose(rc);
        // 是否刷训练本
        doLoTrain(rc, timerTaskExcutor, clickManage, IF_LO);
        doLoDaily(rc);
        // 执行DC挂机任务
        if (IF_DC) {
            DaillyMission.getSpringBean().toggle(false);
        }
        // 执行lo一次循环
        doLoDecompose(rc);
        doLoDaily(rc);
        // 小号刷资源
        ApGudaziFactory.getInstance(qts[0], "small", null).startAllFgo();
        // 主账号刷资源
//        ApGudaziFactory.getInstance(qts[1], "small", null).startAllFgo();
        // 抽奖
        ProcessDealUtil.killAllDnPlayer();
        allRewardAndRoll();
        // dailyChainName finish
        rc.setAutoChainName(autoChainName);
        ChainUtil.saveRunningChain(rc);
        ProcessDealUtil.closeChrome();
        // 执行 lo任务
        if (IF_LO) {
            if (autoChainName.contains("TEAM")) {
            } else {
                clickManage.waitUntilShiftIn();
            }
            // 正常登陆
            timerTaskExcutor.execute(new Runnable() {
                @Override
                public void run() {
                    clickManage.Toggle(autoChainName, false);
                }
            });

        }
        //是否关机
        if (IF_ShutDown_BeforeRunable && !IF_LO) {
            closeComputer();
        }
        if (IF_RUNABLE) {
            GameUtil.delay(5000);
            timerTaskExcutor.execute(new Runnable() {
                @Override
                public void run() {
                    clickManage.doCornRunnable(cornString, runableModuleName);
                }
            });
        }
    }

    public void startMainAccount() throws Exception {
        ApGudaziFactory.getInstance("qp", "big", null).startAllFgo();
    }

    public void mainAccountQP40() throws Exception {
        int[] apArray = {40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40};
        ApGudaziFactory.getInstance("SPqp", "event", apArray).startAllFgo();
    }

    public void mainAccountEXP40() throws Exception {
        int[] expArray = {40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
                , 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40};
        String[] qts = GameUtil.getValueFromConfig("QP_TRAIN_SELECTS").split("_");
        ApGudaziFactory.getInstance("exp", "big", expArray).startAllFgo();

    }

    public void eventingFgo() throws Exception {
        ApGudaziFactory.getInstance("event", "event", null).startAllFgo();
    }

    public void openEvent() throws Exception {
        int account = FgoFrame.getAccount();
        countNum = FgoFrame.getAccount();
        try {
            ProcessDealUtil.startFgoByReplace(account,2);

            AbstractApGudazi.move2WinAndTransferPage(account);

            GameUtil.waitForHomePage();
        } catch (AppNeedNextException | AppNeedRestartException e) {
            openEvent();
        }
    }

    public void updateAllFGO(int vms) throws Exception {
        int[] array = getFgoSignArray();
        int tip;
        int size = array.length;
        ProcessDealUtil.delVmsExcept1();

        for (int i = 0; i < size; i++) {
            tip = array[i];
            countNum = tip;
            // 单个账号行动开启
            try {
                ProcessDealUtil.killAllDnPlayer();
                updateOneFGO(tip,tip);
            } catch (AppNeedNextException e) {
                LOGGER.info(e.getMessage());
            } catch (AppNeedUpdateException e) {
                LOGGER.info(e.getMessage());
                installAllFGO(vms);
                break;
            } finally {

            }
        }
        goAll();
    }

    public void signAllFGO() throws Exception {
        int[] array = getFgoSignArray();
        int account;
        int size = array.length;
        int vms = 2;
        for (int i = 0; i < size; i++) {
            account = array[i];
            countNum = account;
            // 单个账号行动开启
            try {
                ProcessDealUtil.killAllDnPlayer();
                signOneFGO(account,vms);
                //登录签到状态
                CpMissonResults cr = CpMissonResults.getInstance();
                boolean[] accountSignState = cr.getAccountSignState();
                accountSignState[i] = true;
                ChainUtil.saveCpMissonResults(cr);
            } catch (AppNeedNextException e) {
                LOGGER.info(e.getMessage());
            } catch (AppNeedUpdateException e) {
                LOGGER.info(e.getMessage());
//                installAllFGO();
                break;
            } finally {

            }
        }
    }

    public void installAllFGO(int vms) {
        //下载更新包
        ProcessDealUtil.downloadLastestFgo();

        int[] array = getFgoRewardArray();
        int size = array.length;
        for (int i = 0; i < size; i++) {
            installOneFgo(array, i ,vms);
        }
    }

    private void installOneFgo(int[] array, int index, int vms) {
        int tip = array[index];
        countNum = tip;
        // 单个账号行动开启
        try {
            updateAndSignOneFGO(tip,vms);
        } catch (AppNeedNextException e) {
            LOGGER.info(e.getMessage());
        } catch (AppNeedUpdateException e) {
            LOGGER.error(e.getMessage(), e);
            installOneFgo(array, index, vms);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    /**
     * 所有号领奖抽池
     *
     * @throws Exception
     */
    public void allRewardAndRoll() throws Exception {
        int[] array = getFgoRewardArray();
        int size = array.length;
        for (int i = 0; i < size; i++) {
            countNum = array[i];
            // 单个账号行动开启
            try {
                oneRewardAndRoll(array[i]);
                //登录奖励领取状态
                CpMissonResults cr = CpMissonResults.getInstance();
                boolean[] accountRewardState = cr.getAccountRewardState();
                accountRewardState[i] = true;
                ChainUtil.saveCpMissonResults(cr);
            } catch (AppNeedNextException e) {
                LOGGER.info(e.getMessage());
            }
        }
    }

    /**
     * 一个号领奖抽池
     *
     * @param tip 账号
     * @throws Exception 异常
     */
    private void oneRewardAndRoll(int tip) throws Exception {
        try {
            ProcessDealUtil.killAllDnPlayer();
            // 打开账号
            if ("RZH_SERVER".equals(NativeCp.getUserName())) {
                ProcessDealUtil.startAppForServerFgoSpace(tip, false);
            } else {
                ProcessDealUtil.startApp(tip, false);
            }

            // 检测loading
            moveWindowToLeftTop();
            checkLoading();
            // 检测公告
            CommonMethods.open2GudaOrRestart();
            // 等待咕哒子(加号)页面
            GameUtil.waitForHomePage();
            LOGGER.info("开始领取任务奖励");
            // 领取任务奖励
            getRewords();
            LOGGER.info("返回主页");
            // 等待咕哒子(加号)页面
            GameUtil.waitForHomePage();
            // 抽取免费池
            LOGGER.info("抽取免费池");
            pickFreeSummon();
            // 等3秒
            // 关闭游戏
            LOGGER.info("关闭当前游戏");
            closeLDForFGO(tip);
        } catch (AppNeedRestartException e) {
            LOGGER.info(e.getMessage());
            closeLDForFGO(tip);
            oneRewardAndRoll(tip);
        }
    }

    /**
     * 获取任务奖励
     *
     * @throws Exception //
     */
    private void getRewords() throws Exception {
        // 任务按钮gud
        Point p1 = new Point(572, 711);
        GameUtil.getMymouse().mouseMoveByPoint(p1,true,true);

        GameUtil.getMymouse().mousePressAndReleaseForConfirm(null);
        // 获取所列标签奖励
        List<Point> pList = new ArrayList<>();
//		pList.add(new Point(668, 197));// 日常按钮坐标
        pList.add(new Point(803, 200));// 周常按钮坐标
        int size = pList.size();
        Point tempP;
        for (int i = 0; i < size; i++) {
            tempP = pList.get(i);
            GameUtil.delay(3000);
            // 奖励获取
            GameUtil.getMymouse().mouseMoveByPoint(tempP,true,true);

            GameUtil.getMymouse().mousePressAndRelease(GameConstant.DELAY/4);
            // 单标签奖励获取
            getOneTipMissionReward();

        }
        // 截图
        GameUtil.img2file(GameConstant.IMG_EXTEND, PREFIX + "\\账号" + countNum + "_奖励领取情况页面.");
        // 返回按钮
        Point pReturn = new Point(138, 97);// 颜色：109;122;150 Color c = new Color(109, 122, 150);
        GameUtil.getMymouse().mouseMoveByPoint(pReturn,true,true);

        GameUtil.getMymouse().mousePressAndReleaseForConfirm(null);
    }

    private void getOneTipMissionReward() throws AppNeedRestartException, AppNeedStopException, AppNeedUpdateException {
        List<PointColor> pcList = new ArrayList<>();
        // 获取任务过滤按钮的1个坐标1个颜色 （可领取的颜色）
        Point pRewardGet = PointInfo.getInstance().getpRewardGet();
        Color cRewardGet = PointInfo.getInstance().getcRewardGet();
        // 获取任务过滤按钮的1个坐标1个颜色 （可领取的颜色）
        List<Point> rewardclickLists = PointInfo.getInstance().getRewardclickLists();
        // 获取任务过滤按钮的1个坐标1个颜色 （可领取的颜色）
        Point pRewardsGetYes = PointInfo.getInstance().getpRewardsGet();
        // 循环7次尝试获取
        Color temp;
        boolean flag;
        int missionNum = 10;
        int statusMum = 5;

        Point pCompleteLabel = PointInfo.getInstance().getpCompleteLabel();// 完成标签
        Color cCompleteLabel = PointInfo.getInstance().getcCompleteLabel();

        Point pGetRewardClick = new Point(923, 392);// 领取任务点击

        Point pStoneGetAndClose = new Point(641, 582);// 石头领取关闭
        Color cStoneGetAndClose = new Color(115, 115, 115);

        PointColor pcStoneGetAndClose = new PointColor(pStoneGetAndClose, cStoneGetAndClose, true);
        int size = rewardclickLists.size();
        Point tempPoint;
        // 循环4次点击获取按钮，直到可获取状态，判断是否可以获取奖励
        for (int j = 0; j < statusMum; j++) {
            GameUtil.getMymouse().mouseMoveByPoint(pRewardGet,true,true);

            GameUtil.getMymouse().mousePressAndRelease(GameConstant.DELAY/4);
            GameUtil.delay(1000);
            temp = GameUtil.getScreenPixel(pRewardGet);
            flag =(temp.getGreen()+temp.getRed()+temp.getBlue())/3>190;
            if (flag) {
                break;
            }
        }
        GameUtil.delay(3000);
        for (int i = 0; i < size; i++) {
            tempPoint = rewardclickLists.get(i);
            GameUtil.getMymouse().mouseMoveByPoint(tempPoint,true,true);

            GameUtil.getMymouse().mousePressAndRelease(GameConstant.DELAY/4);
            GameUtil.delay(3000);
        }


//        for (int i = 0; i < missionNum; i++) {
//            // 循环4次点击获取按钮，直到可获取状态，判断是否可以获取奖励
//            for (int j = 0; j < statusMum; j++) {
//                GameUtil.mouseMoveByPoint(pRewardGet);
//                GameUtil.mousePressAndRelease(KeyEvent.BUTTON1_DOWN_MASK);
//                temp = GameUtil.getScreenPixel(pRewardGet);
//                flag = GameUtil.likeEqualColor(cRewardGet, temp);
//                if (flag) {
//                    break;
//                }
//            }
//            GameUtil.delay(3000);
//            temp = GameUtil.getScreenPixel(pCompleteLabel);
//            if (GameUtil.likeEqualColor(cCompleteLabel, temp)) {
//                GameUtil.mouseMoveByPoint(pGetRewardClick);
//                GameUtil.mousePressAndReleaseForConfirm(KeyEvent.BUTTON1_DOWN_MASK, pcStoneGetAndClose);
//                pcList = new ArrayList<>();
//                pcList.add(pcStoneGetAndClose);
//                GameUtil.waitUntilAllColor(pcList, DELAY, Constant.FGOMonitor);
//                // 关闭领取弹窗
//                GameUtil.mouseMoveByPoint(pStoneGetAndClose);
//                GameUtil.mousePressAndReleaseForConfirm(KeyEvent.BUTTON1_DOWN_MASK);
//            } else {
//                break;
//            }
//        }
    }

    /**
     * 抽取免费池子
     *
     * @throws Exception 异常
     */
    private void pickFreeSummon() throws Exception {
        // 进入召唤池
        Point p = new Point(1228, 736);// 颜色：144;152;169 Color c = new Color(144, 152, 169);
        GameUtil.getMymouse().mouseMoveByPoint(p,true,true);

        GameUtil.getMymouse().mousePressAndReleaseForConfirm(null);
        Point p1 = new Point(671, 701);// 颜色：46;65;178 Color c = new Color(46, 65, 178);
        GameUtil.getMymouse().mouseMoveByPoint(p1,true,true);

        GameUtil.getMymouse().mousePressAndReleaseForConfirm(new PointColor(PointInfo.getInstance().getpDownPanelClose(),
                PointInfo.getInstance().getcDownPanelClose(), false));
        // 等待石头图标
        List<PointColor> pocoList = new ArrayList<>();
        pocoList.add(new PointColor(PointInfo.getInstance().getpSummonStone(), PointInfo.getInstance().getcSummonStone(), true));
        GameUtil.waitUntilAllColor(pocoList, DELAY, Constant.FGOMonitor);
        // 切换左箭头
        Point p3 = new Point(85, 410);// 颜色：248;244;248 Color c = new Color(248, 244, 248);
        GameUtil.getMymouse().mouseMoveByPoint(p3,true,true);

        GameUtil.getMymouse().mousePressAndRelease(GameConstant.DELAY/4);
        // 等待小手图标
        pocoList = new ArrayList<>();
        pocoList.add(new PointColor(PointInfo.getInstance().getpHand(), PointInfo.getInstance().getcHand(), true));
        GameUtil.waitUntilAllColor(pocoList, DELAY, Constant.FGOMonitor);
        try {
            // 点击确定按钮抽取
            Point p5 = new Point(677, 603);// 颜色：31;167;202
            GameUtil.getMymouse().mouseMoveByPoint(p5,true,true);

            GameUtil.getMymouse().mousePressAndReleaseForConfirm(null);
            Point p6 = new Point(886, 609);
            GameUtil.getMymouse().mouseMoveByPoint(p6,true,true);

            GameUtil.getMymouse().mousePressAndReleaseForConfirm(null);
        } catch (AppNeedRestartException e) {
            LOGGER.info("没有免费池，跳过！");
        }
        // 等待3秒
        r.delay(10 * DELAY);

    }

    /***
     * 签到一个FGO
     *
     * @throws Exception 异常
     */
    private void signOneFGO(int accountNum, int vms) throws Exception {
        try {
            // 打开账号
//            if ("RZH_SERVER".equals(NativeCp.getUserName())) {
//                ProcessDealUtil.startAppForServerFgoSpace(accountNum, false);
//            } else {
//                ProcessDealUtil.startApp(accountNum, false);
//            }
            ProcessDealUtil.startFgoByReplace(accountNum,vms);
            // 检测loading
            moveWindowToLeftTop();
            checkLoading();
            // 检测公告
            CommonMethods.open2GudaOrRestart();
            GameUtil.waitForHomePage();
            // 关闭游戏
            closeLDForFGO(vms);
        } catch (AppNeedRestartException e) {
            closeLDForFGO(vms);
            signOneFGO(accountNum,vms);
        }
    }

    private void updateOneFGO(int tip,int vms) throws Exception {

        if (tip != 1) {
            ProcessDealUtil.cpVmsFromOne();
        }
        ProcessDealUtil.startLdForServerFgoSpace(tip, true);
        boolean flag = true;
        while (flag){
            if(ProcessDealUtil.testLdRunning(tip)){
                flag =false;
            }else{
                ProcessDealUtil.startLdForServerFgoSpace(tip, true);
            }
        }
        GameUtil.delay(20 * 1000);
        ProcessDealUtil.cpAccountFileForFgo(tip,vms);
    }

    private void closeLDForFGO(int accountNum) {
        if ("RZH_SERVER".equals(NativeCp.getUserName())) {
            ProcessDealUtil.closeLDForServerFgoSpace(accountNum);
        } else {
            ProcessDealUtil.closeLD(accountNum);
        }
    }

    /***
     * 签到一个FGO
     *
     * @throws Exception 异常
     */
    private void updateAndSignOneFGO(int index , int vms) throws Exception {
        int a = 0;
        try {
            // 打开窗口
            if ("RZH_SERVER".equals(NativeCp.getUserName())) {
                ProcessDealUtil.startLdForServerFgoSpace(index, false);
            } else {
                ProcessDealUtil.startLd(index, false);
            }
            moveWindowToLeftTop();
            // 安装更新好的apk
            readyUpdateApk(index);
            // 检测loading
            try {
                checkLoading();
            } catch (AppNeedRestartException e) {
                checkLoading();
            }

            // 检测公告
            CommonMethods.open2GudaOrRestart();
            GameUtil.waitForHomePage();
            // 关闭游戏
            closeLDForFGO(index);
        } catch (AppNeedRestartException e) {
            closeLDForFGO(index);
            signOneFGO(index,vms);
        }
    }

    private void moveWindowToLeftTop() throws Exception {
        // 移动窗口至左上角
        Point p1920 = PointInfo.getInstance().getpLeftTop();
        Color c1920 = PointInfo.getInstance().getcLeftTop();
        List<PointColor> pocoList = new ArrayList<>();
        Point p2560 = new Point(662,415);
        Color c2560 = new Color(255,221,0);
        if(Toolkit.getDefaultToolkit().getScreenSize().width == 2560){
            pocoList.add(new PointColor(p2560, c2560, true));
        }else{
            pocoList.add(new PointColor(p1920, c1920, true));
        }
        //我s
        GameUtil.waitUntilAllColor(pocoList, DELAY, Constant.FGOMonitor);
        GameUtil.moveToLeftTop();
    }

    private void readyUpdateApk(int index) throws Exception {
        List<PointColor> pocoList = new ArrayList<>();
        pocoList = new ArrayList<>();
        pocoList.add(new PointColor(PointInfo.getInstance().getpLdIsOpen(), PointInfo.getInstance().getcLdIsOpen(), true, "install"));
        GameUtil.waitUntilOneColor(pocoList, Constant.FGOMonitor);
        if ("RZH_SERVER".equals(NativeCp.getUserName())) {
            ProcessDealUtil.installAppForServerFgoSpace(index);
        } else {
            ProcessDealUtil.installApp(index);
        }
    }

    private void checkLoading() throws Exception {
        // 检测loading是否完毕
        Point pLoading = PointInfo.getInstance().getpLoading();
        Color cLoading = PointInfo.getInstance().getcLoading();

        Point pTransfer = PointInfo.getInstance().getpTransfer();
        Color cTransfer = PointInfo.getInstance().getcTransfer();

        List<PointColor> pcList = new ArrayList<>();
        pcList.add(new PointColor(pLoading, cLoading, PointInfo.getInstance().getDeadPoint(), true));
        List<PointColor> finishPCList = new ArrayList<>();
        finishPCList.add(new PointColor(pTransfer, cTransfer, PointInfo.getInstance().getDeadPoint(), true));
        AutoAct ac = new AutoAct(pcList, finishPCList) {
            @Override
            public void doSomeThing() {
                Color cWait = this.getPcWait().getColor();
                if (GameUtil.likeEqualColor(cTransfer, cWait)) {
                    GameUtil.img2file(GameConstant.IMG_EXTEND, PREFIX + "\\账号" + countNum + "_引继页面.");
                }
            }
        };
        ac.autoAct();
    }



    private void startBalanceForEvent(int count) throws Exception {
        LOGGER.info("结算侦测");
        // 死角点
        Point deadPoint = PointInfo.getInstance().getDeadPoint();
        // 复位点
        Point pReset = PointInfo.getInstance().getpReset();
        // 羁绊三角1
        Point pFetter01 = PointInfo.getInstance().getpFetter01();
        Color cFetter01 = PointInfo.getInstance().getcFetter01();
        // 羁绊三角2
        Point pFetter02 = PointInfo.getInstance().getpFetter02();
        Color cFetter02 = PointInfo.getInstance().getcFetter02();
        // 羁绊升级
        Point pFetterUp = PointInfo.getInstance().getpFetterUp();
        Color cFetterUp = PointInfo.getInstance().getcFetterUp();
        // 确认点
        Point pConfirmRd = PointInfo.getInstance().getpConfirmRd();
        Color cConfirmRd = PointInfo.getInstance().getcConfirmRd();
        //好友申请拒绝点
        Point pGetFriendNo = PointInfo.getInstance().getpGetFriendNo();
        Color cGetFriendNo = PointInfo.getInstance().getcGetFriendNo();
        // 咕哒子
        Point pGuda = PointInfo.getInstance().getpGuda();
        Color cGuda = PointInfo.getInstance().getcGuda();
        // 获取奖励动态坐标颜色
        Point pRewardAction = PointInfo.getInstance().getpRewardAction();
        Color cRewardAction = PointInfo.getInstance().getcRewardAction();

        List<PointColor> pcList = new ArrayList<>();
        pcList.add(new PointColor(pFetter01, cFetter01, pReset, true));
        pcList.add(new PointColor(pFetter02, cFetter02, pReset, true));
        pcList.add(new PointColor(pFetterUp, cFetterUp, pReset, true));
        pcList.add(new PointColor(pConfirmRd, cConfirmRd, pConfirmRd, true));
        pcList.add(new PointColor(pGetFriendNo, cGetFriendNo, pGetFriendNo, true));
        pcList.add(new PointColor(pRewardAction, cRewardAction, pRewardAction, true));
        List<PointColor> finishPCList = new ArrayList<>();
        finishPCList.add(new PointColor(pGuda, cGuda, deadPoint, true));
        AutoAct ac = new AutoAct(pcList, finishPCList) {
            @Override
            public void doSomeThing() {
                Color cWait = this.getPcWait().getColor();
                if (GameUtil.likeEqualColor(cConfirmRd, cWait)) {
                    GameUtil.img2file(IMG_EXTEND, PREFIX + "账号" + countNum + "_第" + count + "战斗奖励页面.");
                }
            }
        };
        ac.autoAct();
    }


    /**
     * 召唤 决定 space 一直按，每按一次 检测一次 颜色 如果锁颜色匹配，点退出按钮 如果menu颜色匹配，继续召唤
     */
    private void summon() {
        int result;
        keyPressAndRelease(KeyEvent.VK_Z);
        r.delay(DELAY);
        keyPressAndRelease(KeyEvent.VK_V);
        do {
            keyPressAndRelease(KeyEvent.VK_SPACE);
            result = checkSummon();
        } while (result == 0);
        if (result == 1) {
            r.delay(DELAY);
            r.delay(DELAY);
            if (checkSummonGotShiJiang() == 0 && checkSummonGotHeiZhen() == 0) {
                keyPressAndRelease(KeyEvent.VK_Q);
                summon();
            }
        }
        if (result == 2) {
            summon();
        }
        if (result == 3) {
            keyPressAndRelease(KeyEvent.VK_Z);
            summon();
        }
        if (result == 4) {
            keyPressAndRelease(KeyEvent.VK_P);
            r.delay(DELAY);
            r.delay(DELAY);
            keyPressAndRelease(KeyEvent.VK_Q);
            summon();
        }
    }

    private int checkSummonGotShiJiang() {
        Color c1 = r.getPixelColor(653, 583);
        if (c1.getRed() == 111 && c1.getGreen() == 91 && c1.getBlue() == 119) {
            return 1;
        }
        return 0;
    }

    private int checkSummonGotHeiZhen() {
        Color c1 = r.getPixelColor(584, 563);
        if (c1.getRed() == 239 && c1.getGreen() == 231 && c1.getBlue() == 198) {
            return 1;
        }
        return 0;
    }

    private int checkSummon() {
        Color c1 = r.getPixelColor(383, 488);
        Color c2 = r.getPixelColor(1487, 889);
        Color c3 = r.getPixelColor(871, 769);
        Color c4 = r.getPixelColor(1622, 237);
        if (c1.getRed() == 229 && c1.getGreen() == 230 && c1.getBlue() == 246) {
            return 1;
        }
        if (c2.getRed() == 222 && c2.getGreen() == 219 && c2.getBlue() == 222) {
            return 2;
        }
        if (c3.getRed() == 215 && c3.getGreen() == 215 && c3.getBlue() == 215) {
            return 3;
        }
        if (c4.getRed() == 214 && c4.getGreen() == 215 && c4.getBlue() == 214) {
            return 4;
        }
        return 0;
    }

    private void keyPressAndRelease(int key) {
        r.keyPress(key);
        r.delay(DELAY);
        r.keyRelease(key);
        r.delay(DELAY);
    }


    public void moveToZero() {
        r.mouseMove(0, 0);
    }

    private void closeComputer() {

        // 执行关机
        ProcessDealUtil.closeComputer();
    }

    public Gudazi() {
        r = GameUtil.getRb();
    }


    public Map<String, List<CommonCard>> getWeakCommondCards(Comparator<CommonCard> comp) {
        Point p_card_click = PointInfo.getInstance().getpCardClick();
        Point p_card_color = PointInfo.getInstance().getpCardColor();
        Point p_card_weak = PointInfo.getInstance().getpCardWeak();
        Point pLoc;
        Point pColor;
        Point pWeak;
        Color cColor;
        CommonCard cc;
        List<CommonCard> ccList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            pLoc = new Point((int) p_card_click.getX() + i * 260, (int) p_card_click.getY());
            pColor = new Point((int) p_card_color.getX() + i * 260, (int) p_card_color.getY());
            pWeak = new Point((int) p_card_weak.getX() + i * 260, (int) p_card_weak.getY());

            cc = new CommonCard();
            cc.setpLoc(pLoc);
            //判断颜色
            cColor = GameUtil.getScreenPixel(pColor);
//			LOGGER.info(cColor.toString());
            ColorVo[] voArray = {new ColorVo(GameConstant.RED, cColor.getRed())
                    , new ColorVo(GameConstant.GREEN, cColor.getGreen())
                    , new ColorVo(GameConstant.BLUE, cColor.getBlue())
            };
            ColorVo tempVo;
            //冒泡排序从小到大
            int num = voArray.length;
            for (int j = 0; j < num; j++) {
                for (int k = 0; k < voArray.length - j - 1; k++) {
                    if (voArray[k].getValue() > voArray[k + 1].getValue()) {
                        tempVo = voArray[k + 1];
                        voArray[k + 1] = voArray[k];
                        voArray[k] = tempVo;
                    }
                }
            }
            //设置排序最大的为颜色
//			LOGGER.info(voArray[voArray.length-1].getColor());
            cc.setCardColor(voArray[voArray.length - 1].getColor());
            //判断克制
            cColor = GameUtil.getScreenPixel(pWeak);
//			LOGGER.info(cColor.toString());
            if (cColor.getGreen() < 50 && cColor.getBlue() < 50) {
                cc.setWeak(true);
            } else {
                cc.setWeak(false);
            }
//			LOGGER.info(cc.isWeak());
            ccList.add(cc);
        }
//		LOGGER.info("======================");
        ccList.sort(comp);
        Map<String, List<CommonCard>> scMap = new HashMap<>();
        List<CommonCard> trueList = new ArrayList<>();
        List<CommonCard> falseList = new ArrayList<>();
        int num = ccList.size();
        for (int i = 0; i < num; i++) {
            CommonCard commonCard = ccList.get(i);
            if (commonCard.isWeak()) {
                trueList.add(commonCard);
            } else {
                falseList.add(commonCard);
            }
        }
        scMap.put("trueList", trueList);
        scMap.put("falseList", falseList);
        return scMap;
    }

    @Override
    public void run() {
        Calendar cd = Calendar.getInstance();
        int h = cd.get(Calendar.HOUR_OF_DAY);
        if (h > 9) {
            this.cancel();
            LOGGER.info("9点以后执行刷本计划！");
            LOGGER.info("此次计划结束后将结束计划并关机！");
        }
        BaseZButton btTemp = FgoFrame.instance().getBts()[3];
        btTemp.setEnabled(btTemp.isEnableStatus());
        btTemp.setExcuteColor();
        btTemp.setExcutebleText();
        btTemp.run();
        if (GameUtil.isSTOP_SCRIPT()) {
            LOGGER.info(">>>>>>>>>>  当前计划已经终止！     <<<<<<<<<<<");
        } else {
            if (h > 9) {
                closeComputer();
                LOGGER.info(">>>>>>>>>>  关机中，请勿操作电脑     <<<<<<<<<<<");
            }
        }
    }

    public static void main(String[] args) {
        int x = new Gudazi().getBattleCount();
        System.out.println(x);
    }
}
